import Http from "../../../btoolkit/network/Http";
import OppoAD from "./OppoAD";
import PopupAlert from "../../components/PopupAlert";
import SDKManager from "../SDKManager";
import ScreenFit from "../../ScreenFit";

const { ccclass, property } = cc._decorator;
@ccclass
export default class OppoBannerUI extends cc.Component {

    whiteTex: cc.SpriteFrame;
    bg: cc.Sprite;
    btnClose: cc.Node;
    icon: cc.Sprite;
    title: cc.Label;
    desc: cc.Label;

    init(): void {
        console.log('已创建BannerUI， 正在进行UI初始化');
        this.node.active = false;
        this.bg.node.on(cc.Node.EventType.TOUCH_START, this.onBgClick, this);
        this.btnClose.on(cc.Node.EventType.TOUCH_START, this.onCloseClick, this);
    }

    /** 显示广告 */
    show(adData: any): void {
        this.node.active = true;
        if (adData.imgUrlList.length > 0) {
            this.loadImg(this.bg, adData.imgUrlList[0]);
            this.icon.node.active = false;
            this.title.node.active = false;
            this.desc.node.active = false;
        } else {
            this.bg.spriteFrame = this.whiteTex;
            this.icon.node.active = true;
            this.title.node.active = true;
            this.desc.node.active = true;
            this.loadImg(this.icon, adData.icon);
            this.title.string = adData.title;
            this.desc.string = adData.desc;
        }
        //设置比例
        let newHeight = 0;
        switch (adData.creativeType) {
            case 6:
                newHeight = this.node.width * 320 / 640;
                this.node.scaleY = newHeight / this.node.height;
                break;
            case 7:
            case 8:
                newHeight = this.node.width * 210 / 320;
                this.node.scaleY = newHeight / this.node.height;
                break;
            default:
                newHeight = OppoAD.bannerUIHeight;
                this.node.scaleY = 1;
                break;
        }
        //高度变了之后，y轴也要改变
        if (this.node.y > ScreenFit.screenSize.height * 0.5) {
            this.node.y = ScreenFit.screenSize.height - newHeight * 0.5;
        } else {
            this.node.y = newHeight * 0.5;
        }
    }

    /** 隐藏广告 */
    hide(): void {
        this.node.active = false;
    }

    /** 下载远程广告 */
    private loadImg(sprite: cc.Sprite, url: string) {
        cc.loader.load(url, (err, tex) => {
            if (err) {
                console.error('[' + url + ']' + err);
                return;
            }
            sprite.spriteFrame = new cc.SpriteFrame(tex);
        });
    }

    /** 背景图点击，相当于点击广告 */
    private onBgClick(): void {
        if (OppoAD.bannerAD) {
            OppoAD.bannerAD.reportAdClick({ adId: OppoAD.data.adId });
        }
    }

    /** 关闭按钮点击 */
    private onCloseClick(): void {
        console.log('点击关闭Banner广告');
        SDKManager.instance.hideBanner(true);
    }

}